package br.com.wss.recursos;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FindCampus {
	private final String URL = "http://200.19.73.182/"
				+ "estrutura-universitaria/pro-reitorias/prograd/catalogo-de-cursos-da-utfpr/";
	private Conexao conexao;
	public FindCampus(){
		
	}
	
	public Map<String, String> find() {
		Map<String, String> map = new HashMap<String, String>();
		InputStream in = null;
		try {
			conexao = new Conexao(URL);
			in = conexao.getConecao();
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db;
			try {
				db = dbf.newDocumentBuilder();
				doc = db.parse(in);
			} catch (ParserConfigurationException e) {
				e.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();
			}
			doc.getDocumentElement().normalize();
			NodeList definitionElements = doc.getElementsByTagName("ul");
			String cidadeDoCursos = "";
			for (int i = 0; i < definitionElements.getLength(); i++) {
				Node itemNode = definitionElements.item(i);
				if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
					Element definitionElement = (Element) itemNode;
					String atributo = definitionElement.getAttribute("class");

					if (atributo.equals("navTree navTreeLevel1")) {
						NodeList cursos = definitionElement
								.getElementsByTagName("a");

						for (int j = 0; j < cursos.getLength(); j++) {
							Element wordDefinitionElement = (Element) cursos
									.item(j);
							String link = wordDefinitionElement
									.getAttribute("href");
							String s1 = URL.substring(0, 21);
							String s2 = link.substring(24, link.length());
							link = s1.concat(s2);
							NodeList nomeCursos = wordDefinitionElement
									.getElementsByTagName("span");
							Element cidade = (Element) nomeCursos.item(0);
							NodeList cursoss = ((Node) cidade).getChildNodes();
							cidadeDoCursos = cursoss.item(0).getNodeValue();
							map.put(cidadeDoCursos, link);
						}
					}
				}
			}
			// }
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return map;
	}
}
